$pop="AFA";
$indir="/data4/bsi/bioinf_ext2/s109990/m081429_mesa/FINAL_MERGING/temp/$pop";
if(-e "$indir/unfiltered.bed")
        {
                system("rm $indir/unfiltered.bed");
        }

for($i=1;$i<24;$i++)
{
	if($i==23)
	{
		$chr="X";
	}
	else
	{
		$chr=$i;
	}
	$sys = "gunzip -c $indir/$i/Combined_impute_results_3_prob_ambi_out.gz |grep -v position|awk -F ' ' '{print \"chr$chr\\t\"\$1\"\\t\"\$1+1\"\\t\"\$2}'>>$indir/unfiltered.bed";	
	system($sys);
}
$sys="intersectBed -wo -a /data4/bsi/bioinf_ext2/s109990/m081429_mesa/FINAL_MERGING/temp/gene_info.bed -b $indir/unfiltered.bed > /data4/bsi/bioinf_ext2/s109990/m081429_mesa/FINAL_MERGING/temp/unfiletered.out";
print $sys."\n";
if(-e "$indir/temp1")
        {
                system("rm $indir/temp1");
        }
        if(-e "$indir/temp2")
        {
                system("rm $indir/temp2");
        }

for($i=1;$i<24;$i++)
{
        if($i==23)
        {
                $chr="X";
        }
        else
        {
                $chr=$i;
        }
        $sys = "gunzip -c $indir/$i/Combined_impute_results_3_prob_ambi_out.gz |grep -v position|awk -F ' ' '{print \"chr$chr\\t\"\$1\"\\t\"\$1+1\"\\t\"\$2}'>>$indir/temp1";
        #print "$sys\n";
        system($sys);
	$sys="gunzip -c $indir/$i/beagle_r2.gz |cut -f1,5 >>$indir/temp2";
	#print "$sys\n";
	system($sys);
	#system($sys);
}
$sys="paste $indir/temp1 $indir/temp2 > $indir/r2_file";
print $sys."\n";
system($sys);
$sys="awk '{if(\$6>0.3)print \$1\"\\t\"\$2\"\\t\"\$3\"\\t\"\$4}' $indir/r2_file > $indir/filtered_r2_0_03.bed";
print $sys."\n";
system($sys);
$sys="intersectBed -wo -a /data4/bsi/bioinf_ext2/s109990/m081429_mesa/FINAL_MERGING/temp/gene_info.bed -b $indir/filtered_r2_0_03.bed > /data4/bsi/bioinf_ext2/s109990/m081429_mesa/FINAL_MERGING/temp/filetered_r2_0_03.out";
print $sys."\n";
system($sys);
$sys="awk '{if(\$6>0.8)print \$1\"\\t\"\$2\"\\t\"\$3\"\\t\"\$4}' $indir/r2_file > $indir/filtered_r2_0_08.bed";
print $sys."\n";
system($sys);
$sys="intersectBed -wo -a /data4/bsi/bioinf_ext2/s109990/m081429_mesa/FINAL_MERGING/temp/gene_info.bed -b $indir/filtered_r2_0_08.bed > /data4/bsi/bioinf_ext2/s109990/m081429_mesa/FINAL_MERGING/temp/filetered_r2_0_08.out";
print $sys."\n";
system($sys);

